<template>
  <div class="editor-container" :style="{ height: '100%', width: '100%' }">
    <Toolbar
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
      class="toolbar"
    />
    <Editor
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
      @onChange="handleChange"
      class="editor"
      :readOnly="readOnlyFlag"
    />
  </div>
</template>

<script setup lang="ts">
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { Boot } from "@wangeditor/editor";
import attachmentModule from "@wangeditor/plugin-upload-attachment";
import { IEditorConfig, IToolbarConfig } from "@wangeditor/editor";
import { watch, onBeforeUnmount, nextTick, ref, shallowRef, onMounted } from "vue";
import { addImage01 } from "@/api/common/work/SelectWork.js";
import { ElMessage } from "element-plus";

// 自定义上传图片逻辑
const customUpload = async (file: File, insertFn: Function) => {
  const maxSize = 5 * 1024 * 1024; // 5MB
  if (file.size > maxSize) {
    ElMessage.error(`图片大小不能超过 ${maxSize / (1024 * 1024)} MB`);
    return;
  }
  try {
    const formData = new FormData();
    formData.append('file', file);
    const response = await addImage01(formData);
    if (response && response.code === 200 && response.data && response.data.data && response.data.data.length > 0) {
      const imageUrl = response.data.data[0].url;
      insertFn(imageUrl);
    } else {
    }
  } catch (error) {
    ElMessage.error('图片上传错误:', error);
  }
};

// Props：使用属性，子组件接收父组件传递的内容
const props = defineProps({
  // 内容
  content: { type: String, default: '' },
  // 编辑器高度，默认500px
  editorHeight: { type: String, default: '490px' },
  // 只读标志
  readOnlyFlag: { type: Boolean, default: false }
});

// Emits：使用事件，将子组件内容传递给父组件。父组件使用 update(content: string)
const emit = defineEmits<{ (e: 'update', content: string): void }>();

const mode = ref('default');

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 内容 HTML
const valueHtml = ref('');

// 定义 handlePaste 函数
const handlePaste = (editor: any, event: ClipboardEvent) => {
  // 获取粘贴的内容
  const clipboardData = event.clipboardData || window.clipboardData;
  const pastedData = clipboardData.getData('text/plain');

  // 处理粘贴的内容
  editor.insertText(pastedData.replace(/\n/g, '\n')); // 保留换行符
};

const editorConfig: Partial<IEditorConfig> = {
  hoverbarKeys: {
    attachment: {
      menuKeys: [],
    },
  },
  MENU_CONF: {
    // 移除 uploadAttachment 相关配置
    pasteFilterStyle: true,
    pasteIgnoreImg: false,
    pasteTextHandle: (text: string) => {
      return text.replace(/\n/g, '<br>');
    },
    onPaste: handlePaste
  },
  placeholder: '请输入内容...'
};

const toolbarConfig: Partial<IToolbarConfig> = {
  insertKeys: {
    index: 0,
    keys: []
  },
};

// 上传图片配置
editorConfig.MENU_CONF['uploadImage'] = {
  fieldName: 'file',
  customUpload, // 使用自定义上传函数
  maxSize: 5 * 1024 * 1024, // 设置最大图片大小为 5MB
};

const handleCreated = (editor: any) => {
  editorRef.value = editor;

  // 根据父组件传递的readOnlyFlag，设置编辑器为只读
  if (props.readOnlyFlag) {
    editorRef.value.disable();
  } else {
    editorRef.value.enable();
  }

  // 确保 config 对象存在
  if (!editorRef.value.config) {
    editorRef.value.config = {};
  }

  // 确认 customUpload 方法正确绑定
  if (!editorRef.value.config.MENU_CONF) {
    editorRef.value.config.MENU_CONF = {};
  }

  if (!editorRef.value.config.MENU_CONF.uploadImage) {
    editorRef.value.config.MENU_CONF.uploadImage = {};
  }

  editorRef.value.config.MENU_CONF.uploadImage.customUpload = customUpload;

  // 处理初始内容
  if (props.content) {
    editorRef.value.setHtml(props.content);
    valueHtml.value = props.content;
  }

  // 绑定全屏事件
  editorRef.value.on('fullScreen', handleFullScreen);
  editorRef.value.on('unFullScreen', handleUnFullScreen);
};

const handleChange = () => {
  valueHtml.value = editorRef.value.getHtml();
  emit('update', valueHtml.value);
};

// 监听 props 变化，监听父组件传来的content
watch(() => props.content, (newVal: string) => {
  nextTick(() => {
    if (editorRef.value) {
      editorRef.value.setHtml(newVal);
      valueHtml.value = newVal;
    }
  });
});

onMounted(async () => {
  await nextTick();
  if (props.content) {
    valueHtml.value = props.content;
  }
});

// 组件销毁时，销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor) {
    editor.destroy();
  }
});

// 全屏处理函数
const handleFullScreen = () => {
  const container = document.querySelector('.editor-container');
  if (container) {
    container.style.position = 'fixed';
    container.style.top = '0';
    container.style.left = '0';
    container.style.width = '100vw';
    container.style.height = '100vh';
    container.style.zIndex = '9999';
    container.style.margin = '0';
    container.style.padding = '0';
    container.style.backgroundColor = 'white';
  }
};

// 取消全屏处理函数
const handleUnFullScreen = () => {
  const container = document.querySelector('.editor-container');
  if (container) {
    container.style.position = '';
    container.style.top = '';
    container.style.left = '';
    container.style.width = '';
    container.style.height = '';
    container.style.zIndex = '';
    container.style.margin = '';
    container.style.padding = '';
    container.style.backgroundColor = '';
  }
};
</script>

<style scoped>
.editor-container {
  display: flex;
  flex-direction: column;
  border: 1px solid #ccc;
  height: 100%;
  width: 100%; /* 确保宽度自适应 */
}

.toolbar {
  border-bottom: 1px solid #ccc;
}

.editor {
  flex: 1;
  overflow-y: auto;
  white-space: pre-wrap;
  width: 100%; /* 确保宽度自适应 */
}

</style>